import React, { useEffect, useRef } from 'react';

/**
 * 极坐标配置接口
 */
export interface PolarConfig {
  radius: [string, string]; // 内外半径百分比
}

/**
 * 角度轴配置接口
 */
export interface AngleAxisConfig {
  max: number;             // 轴最大值
  startAngle: number;      // 起始角度
  axisLine: { show: boolean };
  axisTick: { show: boolean };
  axisLabel: { show: boolean };
  splitLine: { show: boolean };
}

/**
 * 半径轴配置接口
 */
export interface RadiusAxisConfig {
  type: 'category';
  axisLine: { show: boolean };
  axisTick: { show: boolean };
  axisLabel: { show: boolean };
  splitLine: { show: boolean };
}

/**
 * 提示框配置接口
 */
export interface TooltipConfig {
  [key: string]: any;
}

/**
 * SummaryChart组件的配置接口
 */
export interface SummaryChartConfig {
  polar?: PolarConfig;
  angleAxis?: AngleAxisConfig;
  radiusAxis?: RadiusAxisConfig;
  tooltip?: TooltipConfig;
}

/**
 * 图表系列数据接口
 */
export interface SeriesData {
  name: string;
  data: number[];
  stack: string;
  color: string;
  emphasis: {
    focus: string;
  };
}

/**
 * SummaryChart组件的数据接口
 */
export interface SimplifiedSummaryData {
  /** 极坐标半径轴数据 */
  radiusAxisData: string[];
  /** CR数据数组 */
  crData: number[];
}

/**
 * SummaryChart组件的属性接口
 */
export interface SummaryChartProps {
  /** 简化的图表数据源 */
  data: SimplifiedSummaryData;
  /** 图表配置项 */
  config?: SummaryChartConfig;
}
import * as echarts from 'echarts';
import { convertX, convertY, convertSize } from '../utils/responsive';
import '../css/summary-chart.css';

/**
 * 数据概览图表组件
 * 定位: x=22, y=75, 尺寸: w=360, h=300 (原型坐标)
 */
const SummaryChart: React.FC<SummaryChartProps> = ({ data, config }) => {
  const chartRef = useRef<HTMLDivElement>(null);
  const chartInstance = useRef<echarts.EChartsType | null>(null);

  // 初始化图表
  useEffect(() => {
    console.log('Chart container ref:', chartRef.current);
    if (chartRef.current) {
      // 检查容器尺寸
      const containerStyle = window.getComputedStyle(chartRef.current);
      console.log('Container dimensions:', containerStyle.width, containerStyle.height);
      
      try {
            chartInstance.current = echarts.init(chartRef.current);
            console.log('ECharts instance created successfully');

            // 预设CR和RW的颜色方案
            const crColors = ['#8cc3ff', '#6ea5ff', '#5087ec'];
            const rwColors = ['#a4d6dc', '#86c9d0', '#68bbc4'];

            // 处理crData为二维数组并计算rwData
            const formattedCrData = data.crData.map((value, index) => {
              const arr = new Array(data.crData.length).fill(0);
              arr[index] = value;
              return arr;
            });

            const formattedRwData = data.crData.map((value, index) => {
              const arr = new Array(data.crData.length).fill(0);
              arr[index] = 1 - value;
              return arr;
            });

            // 自动生成系列数据
            const series = [];
            for (let i = 0; i < formattedCrData.length; i++) {
              series.push({
                name: 'CR',
                data: formattedCrData[i],
                stack: 'a',
                color: crColors[i % crColors.length],
                emphasis: { focus: 'series' }
              });
              series.push({
                name: 'RW',
                data: formattedRwData[i],
                stack: 'a',
                color: rwColors[i % rwColors.length],
                emphasis: { focus: 'series' }
              });
            }

            // 默认配置
            const defaultConfig: Required<SummaryChartConfig> = {
              polar: {
                radius: ['24%', '95%']
              },
              angleAxis: {
                max: 1,
                startAngle: 75,
                axisLine: { show: true },
                axisTick: { show: false },
                axisLabel: { show: false },
                splitLine: { show: false }
              },
              radiusAxis: {
                type: 'category',
                axisLine: { show: true },
                axisTick: { show: false },
                axisLabel: { show: false },
                splitLine: { show: false }
              },
              tooltip: {}
            };

            // 合并默认配置和用户配置
            const mergedConfig = { ...defaultConfig, ...config };

            const option = {
              polar: mergedConfig.polar,
              angleAxis: mergedConfig.angleAxis,
              radiusAxis: {
                ...mergedConfig.radiusAxis,
                data: data.radiusAxisData
              },
              tooltip: mergedConfig.tooltip,
              series: series.map(seriesItem => ({
                type: 'bar',
                coordinateSystem: 'polar',
                ...seriesItem
              }))
            };

            chartInstance.current.setOption(option);
            console.log('Chart option set successfully');
          } catch (error) {
            console.error('Error initializing ECharts:', error);
          }

        // 响应窗口大小变化
        const handleResize = () => {
          if (chartInstance.current) {
            chartInstance.current.resize();
          }
        };
        window.addEventListener('resize', handleResize);

        

      return () => {
        window.removeEventListener('resize', handleResize);
        chartInstance.current?.dispose();
      };
    } else {
      console.error('Chart container element is null');
    }
  }, [data, config]);

  // 添加错误边界处理
  useEffect(() => {
    return () => {
      if (chartInstance.current) {
        chartInstance.current.dispose();
        chartInstance.current = null;
      }
    };
  }, []);

  return (
    <div
      ref={chartRef}
      className="summary-chart"
      style={{
        position: 'absolute',
        left: convertX(22),
        top: convertY(55),
        width: convertSize(360),
        height: convertSize(300, false),
      }}
    />
  );
};

export default SummaryChart;